package cn.pzhu.pserson.controller;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.pzhu.pserson.model.Peoplenum;
import cn.pzhu.pserson.service.IPeoplenumService;
import cn.pzhu.pserson.service.IPrizeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import cn.pzhu.pserson.util.ResponseUtil;
import cn.pzhu.pserson.dto.UserinfoDTO;
import cn.pzhu.pserson.model.Userinfo;
import cn.pzhu.pserson.dto.LimitShowDTO;
import cn.pzhu.pserson.service.IUserinfoService;


@Controller
@RequestMapping("/userinfo")
public class UserinfoController {
    @Autowired
    private IUserinfoService userinfoService;

    @Autowired
    private IPrizeService prizeService;

    @Autowired
    private IPeoplenumService peoplenumService;


    @CrossOrigin
    @RequestMapping(value = "/share", method = RequestMethod.POST, produces = {"text/plain;charset=utf-8","text/html;charset=utf-8"}             )
    @ResponseBody
    public ResponseEntity<String> share(
            @Validated
                    LimitShowDTO limitShowDTO, BindingResult errors, HttpServletResponse response,HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();

        String ip = request.getParameter("uuid");
        if(ip == null || "".equals(ip) || "null".equals(ip)){
//            return ResponseUtil.getResEntityForGet(ResponseUtil.FAIL_RS)
            ip = getIpAddr(request);
        }
        String type = request.getParameter("type");

        List<Userinfo> userinfos = userinfoService.loadModels("ip=?",new String[]{ip},null,null,0,1);
        Userinfo userinfo = userinfos.get(0);
        if(userinfo != null){
            switch (type){
                case "1":
                    if(userinfo.getIfshare() == 0){
                        userinfo.setCount(userinfo.getCount() + 1);
                        userinfo.setIfshare(1);
                        userinfoService.update(userinfo);

                        Peoplenum peoplenum =  peoplenumService.loadModels().get(0);
                        peoplenum.setFxNum(peoplenum.getFxNum() + 1);
                        peoplenumService.update(peoplenum);
                    }
                    break;
                case "2":
                    if(userinfo.getIfquan() == 0){
                        userinfo.setCount(userinfo.getCount() + 1);
                        userinfo.setIfquan(1);
                        userinfoService.update(userinfo);

                        Peoplenum peoplenum =  peoplenumService.loadModels().get(0);
                        peoplenum.setPyqNum(peoplenum.getPyqNum() + 1);
                        peoplenumService.update(peoplenum);
                    }
                    break;
            }
        }else{
            result.put("message","分享失败，请重新打开页面重试");
        }

        return ResponseUtil.getResEntityForGetAndJson(result);
    }

    @CrossOrigin
    @RequestMapping(value = "/infoOpenid", method = RequestMethod.POST, produces = {"text/plain;charset=utf-8","text/html;charset=utf-8"}             )
    @ResponseBody
    public ResponseEntity<String> infoOpenid(
            @Validated
                    LimitShowDTO limitShowDTO, BindingResult errors, HttpServletResponse response,HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();


        String ip = cn.pzhu.pserson.util.jssdk.getOpenid(request.getParameter("uuid"));

        result.put("openid", ip);
        return ResponseUtil.getResEntityForGetAndJson(result);
    }

    @CrossOrigin
    @RequestMapping(value = "/info", method = RequestMethod.POST, produces = {"text/plain;charset=utf-8","text/html;charset=utf-8"}             )
    @ResponseBody
    public ResponseEntity<String> info(
            @Validated
                    LimitShowDTO limitShowDTO, BindingResult errors, HttpServletResponse response,HttpServletRequest request) {

        Map<String, Object> result = new HashMap<String, Object>();

        String ip = request.getParameter("uuid");
        if(ip != null && !"undefind".equals(ip)) {
            List<Userinfo> userinfo = userinfoService.loadModels("ip=?", new String[]{ip}, null, null, 0, 1);
            if (userinfo.size() <= 0) {
                Userinfo userinfo1 = new Userinfo();
                userinfo1.setIp(ip);
                userinfo1.setIfquan(0);
                userinfo1.setIfshare(0);
                userinfo1.setCount(3);
                userinfo1.setAttr1("0");
                Boolean flag = userinfoService.save(userinfo1);
                if (flag) {
                    result.put("info", userinfo1);
                } else {
                    return ResponseUtil.getResEntityForGet(ResponseUtil.FAIL_RS);
                }
            } else {
                long count = prizeService.count("ip=? and to_days(createtime) = to_days(now())", new String[]{ip});
                Integer zong = 3;
                Userinfo userinfo1 = userinfo.get(0);
                Integer cjcount = userinfo1.getCount();
                if(count == 0) {
                    userinfo1.setIfquan(0);
                    userinfo1.setIfshare(0);
                    userinfoService.update(userinfo1);
                }
                if(userinfo1.getIfquan() == 1){
                    zong += 1;
                }
                if(userinfo1.getIfshare() == 1){
                    zong += 1;
                }
                Integer sumcount = Integer.parseInt((zong - count) + "");
                if(cjcount != sumcount){
                    userinfo1.setCount((sumcount <0? 0: sumcount));
                    userinfoService.update(userinfo1);
                }

                result.put("info", userinfo1);
            }

            List<Peoplenum> peoplenumList = peoplenumService.loadModels(null, null, null, null, limitShowDTO.getPageNum(), limitShowDTO.getPageNum());

            Peoplenum peoplenum = peoplenumList.get(0);

            result.put("wg", peoplenum.getWgNum());

            result.put("cy", prizeService.count(new String[]{"ip"},true));
        }else{
            result.put("message", "用户openid丢失");
        }
        return ResponseUtil.getResEntityForGetAndJson(result);
    }


    public String getIpAddr(HttpServletRequest request){
        String ipAddress = request.getHeader("x-forwarded-for");
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress= inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
            if(ipAddress.indexOf(",")>0){
                ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ResponseEntity<String> list(
        @Validated
        LimitShowDTO limitShowDTO, BindingResult errors) {
        if(errors.hasErrors())
            return ResponseUtil.getResponseEntityWhenInvalidReqParams();

        Map<String, Object> result = new HashMap<String, Object>();

        List<Map<String, Object>> userinfoList = userinfoService.loadMaps(null, null, null, null, limitShowDTO.getPageNum(), limitShowDTO.getPageSize());
        long count = userinfoService.count();

        result.put("rows", userinfoList);
        result.put("total", count);

        return ResponseUtil.getResEntityForGetAndJson(result);
    }

    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResponseEntity<String> show(String ip) {
        Map<String, Object> userinfoModel = userinfoService.findMap(ip);

        return ResponseUtil.getResEntityForGetAndJson(userinfoModel);
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResponseEntity<String> create(
        @Validated
        UserinfoDTO userinfoDTO, BindingResult errors) {
        if(errors.hasErrors())
            return ResponseUtil.getResponseEntityWhenInvalidReqParams();

        Userinfo userinfoModel = userinfoDTO.toModel();

        return ResponseUtil.getResEntityForPPP(userinfoService.save(userinfoModel));
    }

    @RequestMapping(value = "", method = RequestMethod.PUT)
    public ResponseEntity<String> update(
        @Validated
        UserinfoDTO userinfoDTO, BindingResult errors) {

        Userinfo userinfoModel = userinfoDTO.toModel();
        return ResponseUtil.getResEntityForPPP(userinfoService.update(userinfoModel));
    }

    @RequestMapping(value = "", method = RequestMethod.DELETE)
    public ResponseEntity<String> destory(String ip) {
        return ResponseUtil.getResEntityForDel(userinfoService.delete(ip));
    }

}
